package com.zoho.daliansheng.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zoho.daliansheng.common.U8SystemRecord;
import com.zoho.daliansheng.common.ZohoRecord;
import com.zoho.daliansheng.config.CRMPathConfig;
import com.zoho.daliansheng.config.DatasourceEnum;
import com.zoho.daliansheng.config.U8SystemPathConfig;
import com.zoho.daliansheng.dlcr.DlcrU8WebService;
import com.zoho.daliansheng.dlcr.DlcrU8WebServiceSoap;
import com.zoho.daliansheng.dlcr.QueryRetInfo;
import com.zoho.daliansheng.utils.CrmApiUtil;
import com.zoho.daliansheng.utils.getCrmFieldUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CustomerAuthServiceImpl implements CustomerAuthService {

    ZohoRecord zohoRecord;

    U8SystemRecord u8SystemRecord;

    U8SystemPathConfig u8SystemPathConfig;

    CRMPathConfig crmPathConfig;

    public CustomerAuthServiceImpl(ZohoRecord zohoRecord, U8SystemRecord u8SystemRecord, U8SystemPathConfig u8SystemPathConfig, CRMPathConfig crmPathConfig) {
        this.zohoRecord = zohoRecord;
        this.u8SystemRecord = u8SystemRecord;
        this.u8SystemPathConfig = u8SystemPathConfig;
        this.crmPathConfig = crmPathConfig;
    }

    @Override
    public void sysCustomerAuth() {

        /*
         * 1 获取CRM 客户管理维度
         */
        List<String> fieldList = getCrmFieldUtil.getCustomerAuthFieldList();
        List<JSONObject> crmData = CrmApiUtil.getModuleData(zohoRecord.getAccessToken(), crmPathConfig.getCustomerAuthModuleName(), fieldList);
        /*
         * 2 同步ERP管理维度
         */
        try {
            synU8Data(crmData, DatasourceEnum.GONG_CHANG.getWebServiceUrl(), DatasourceEnum.GONG_CHANG.getCompanyName(), DatasourceEnum.GONG_CHANG.getAccountCode());
            synU8Data(crmData, DatasourceEnum.SU_ZHOU.getWebServiceUrl(), DatasourceEnum.SU_ZHOU.getCompanyName(), DatasourceEnum.SU_ZHOU.getAccountCode());
            synU8Data(crmData, DatasourceEnum.CHANG_ZHOU.getWebServiceUrl(), DatasourceEnum.CHANG_ZHOU.getCompanyName(), DatasourceEnum.CHANG_ZHOU.getAccountCode());
            synU8Data(crmData, DatasourceEnum.DA_LIAN.getWebServiceUrl(), DatasourceEnum.DA_LIAN.getCompanyName(), DatasourceEnum.DA_LIAN.getAccountCode());
            synU8Data(crmData, DatasourceEnum.XIN_CAI_LIAO.getWebServiceUrl(), DatasourceEnum.XIN_CAI_LIAO.getCompanyName(), DatasourceEnum.XIN_CAI_LIAO.getAccountCode());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void synU8Data(List<JSONObject> crmData, String webServiceUrl, String companyName, String accountCode) throws MalformedURLException {

        String synModuleName = crmPathConfig.getCustomerAuthModuleName();

        // 1 过滤CRM数据，只保留单一账套
        crmData = crmData.stream().filter(object -> Objects.nonNull(object.getString("KHCompany")) && object.getString("KHCompany").equals(companyName)).collect(Collectors.toList());

        // 2 获取ERP数据
        DlcrU8WebService webService = new DlcrU8WebService(new URL(webServiceUrl));
        DlcrU8WebServiceSoap api = webService.getDlcrU8WebServiceSoap();
        QueryRetInfo queryRetInfo = api.queryAuthDimenSub();
        JSONArray jsonArray = JSONArray.parseArray(queryRetInfo.getJson());
        System.out.println("jsonArray.size() = " + jsonArray.size());
        if (jsonArray.size() > 0) {

            // 4 比较数据
            List<JSONObject> insertList = new ArrayList<>();
            List<JSONObject> updateList = new ArrayList<>();
            List<JSONObject> batchAuth = jsonArray.toJavaList(JSONObject.class);

            for (JSONObject auth : batchAuth) {

                String authCode = auth.getString("cadcode"); // 权限维度编码
                List<JSONObject> searchList = crmData.stream().filter(object -> Objects.nonNull(object.getString("cADCode")) && object.getString("cADCode").equals(authCode)).collect(Collectors.toList());

                if (searchList.size() > 0) {
                    JSONObject jsonObject = searchList.get(0);
                    String crmId = jsonObject.getString("id");
                    auth.put("crmId", crmId);
                    updateList.add(auth);
                } else {
                    insertList.add(auth);
                }
            }

            // 5 字段映射
            List<JSONObject> crm_insertList = getCrmMappingData(insertList, accountCode, companyName);
            List<JSONObject> crm_updateList = getCrmMappingData(updateList, accountCode, companyName);
            System.out.println("crm_insertList.size() = " + crm_insertList.size());
            System.out.println("crm_updateList.size() = " + crm_updateList.size());

            // 6 批量操作
            CrmApiUtil.batchInsertDataByList(zohoRecord.getAccessToken(), crm_insertList, synModuleName);
            CrmApiUtil.batchUpdateDataByList(zohoRecord.getAccessToken(), crm_updateList, synModuleName);
        }

    }

    private List<JSONObject> getCrmMappingData(List<JSONObject> erpList, String accountCode, String companyName) {
        List<JSONObject> list = new ArrayList<>();
        for (JSONObject erpData : erpList) {
            JSONObject crmData = new JSONObject();
            String crmId = erpData.getString("crmId");
            if (StringUtils.isNotBlank(crmId)) {
                crmData.put("id", crmId);
            }
            crmData.put("cADCode", erpData.getString("cadcode")); // 权限维度编码
            crmData.put("Name", erpData.getString("cadname")); // 权限维度名称
            crmData.put("account_name", accountCode); // 账套
            crmData.put("KHCompany", companyName); // 所属公司
            crmData.put("type_code", "5"); // 维度分类编码
            list.add(crmData);
        }
        return list;
    }
}
